package org.dylan.bdf.system.service;

import org.apache.commons.lang3.StringUtils;
import org.dylan.bdf.system.dao.DeptDao;
import org.dylan.bdf.system.dao.RoleDao;
import org.dylan.bdf.system.dao.UserDao;
import org.dylan.bdf.system.entity.Dept;
import org.dylan.bdf.system.entity.Role;
import org.dylan.bdf.system.entity.User;
import org.dylan.bdf.system.model.LogLevel;
import org.dylan.bdf.system.model.LogType;
import org.dylan.common.paging.PageData;
import org.dylan.common.paging.PageRequest;
import org.dylan.security.service.PasswordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SystemService {

	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleDao roleDao;

	@Autowired
	private DeptDao deptDao;

	@Autowired
	private PasswordService passwordService;

	@Autowired
	private LogService logService;

	public User findUser(String userId) {
		return userDao.findOne(userId);
	}

	public void saveUser(User user) {
		if(StringUtils.isBlank(user.getId())){
			//新用户
			logService.addLog(LogLevel.info, LogType.type(LogType.Type.userManage.name()), "新增用户["+user.getUsername()+"]");
		} else {
			//编辑用户
			logService.addLog(LogLevel.info, LogType.type(LogType.Type.userManage.name()), "编辑用户["+user.getUsername()+"]");
		}
		userDao.save(user);
	}

	public PageData<User> findUserByPage(PageRequest pageRequest) {
		return userDao.findByPage(pageRequest);
	}

	public PageData<Role> findRoleByPage(PageRequest pageRequest) {
		return roleDao.findByPage(pageRequest);
	}

	public Role findRole(String id) {
		return roleDao.findOne(id);
	}

	public void disableUser(User user) {
		userDao.disableUser(user.getId());
	}

	public void enableUser(User user) {
		userDao.enableUser(user.getId());
	}

	public void saveRole(Role role) {
		roleDao.save(role);
	}

	public Iterable<Dept> getAllDepts() {
		return deptDao.findAll();
	}

	public void saveDept(Dept dept) {
		if (StringUtils.isEmpty(dept.getId())) {
			dept.setId(null);
		}
		deptDao.save(dept);
	}

	public void changePassword(User user, String encryptPassword) {
		userDao.changePassword(user.getId(),encryptPassword);
	}
}
